<template>
  <a-modal
    :title="modalTitle"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="取消"
    okText="确定"
  >
    <a-form-model
      ref="form"
      :model="model"
      :rules="validatorRules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
    >
      <!-- 基本信息 -->
      <a-card title="基本信息" size="small" style="margin-bottom: 16px">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-model-item label="出库单号" prop="outboundNo">
              <a-input v-model="model.outboundNo" placeholder="系统自动生成" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="订单编号" prop="orderNo">
              <j-select-production-order-modal
                v-model="model.orderNo"
                placeholder="请选择订单"
                :status="10"
                :multiple="false"
                title="选择已入库订单"
                @change="handleOrderChange"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="客户名称">
              <a-input v-model="model.customerName" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-model-item label="项目名称">
              <a-input v-model="model.projectName" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="出库总数">
              <a-input-number v-model="model.totalQuantity" :min="0" disabled style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-form-model-item label="备注" prop="remark">
          <a-textarea v-model="model.remark" placeholder="请输入备注信息" :rows="2" />
        </a-form-model-item>
      </a-card>

      <!-- 订单明细 -->
      <a-card title="订单明细" size="small" v-if="orderDetailList.length > 0">
        <a-table
          :columns="detailColumns"
          :dataSource="orderDetailList"
          :pagination="false"
          size="small"
          rowKey="id"
          :row-selection="rowSelection"
          :expandedRowKeys="expandedRowKeys"
          @expand="handleExpand"
          :expandRowByClick="true"
        >
          <template slot="expandedRowRender" slot-scope="record">
            <a-table
              :columns="inventoryColumns"
              :dataSource="record.inventoryList || []"
              :pagination="false"
              size="small"
              :rowKey="(record, index) => record.orderDetailId || index"
              style="margin: 0"
            >
              <template slot="availableQuantity" slot-scope="text">
                <span :style="{ color: text > 0 ? '#52c41a' : '#ff4d4f' }">{{ text }}</span>
              </template>
            </a-table>
          </template>

          <template slot="availableQuantity" slot-scope="text">
            <span :style="{ color: text > 0 ? '#52c41a' : '#ff4d4f' }">{{ text }}</span>
          </template>

          <template slot="action" slot-scope="text, record">
            <a @click="toggleExpand(record)">
              {{ expandedRowKeys.includes(record.id) ? '收起' : '查看库存' }}
            </a>
          </template>
        </a-table>
      </a-card>
    </a-form-model>
  </a-modal>
</template>

<script>
import JSelectProductionOrderModal from '@/components/jeecgbiz/JSelectProductionOrderModal.vue'

export default {
  name: 'FinishedGoodsOutboundModal',
  components: {
    JSelectProductionOrderModal,
  },
  data() {
    return {
      modalTitle: '新增出库单',
      visible: false,
      confirmLoading: false,
      model: {},
      orderDetailList: [],
      selectedRowKeys: [],
      expandedRowKeys: [],
      validatorRules: {
        orderNo: [{ required: true, message: '请选择订单!' }],
      },
      detailColumns: [
        { title: '门窗编号', dataIndex: 'windowNo', width: 120 },
        { title: '门窗系列', dataIndex: 'windowSeries', width: 150 },
        { title: '门窗颜色', dataIndex: 'windowColor', width: 150 },
        { title: '订单数量', dataIndex: 'quantity', width: 100 },
        { title: '总面积(㎡)', dataIndex: 'totalArea', width: 100 },
        { title: '总重量(kg)', dataIndex: 'totalWeight', width: 100 },
        {
          title: '操作',
          width: 80,
          scopedSlots: { customRender: 'action' },
        },
      ],
      inventoryColumns: [
        { title: '仓库', dataIndex: 'warehouseName', width: 120 },
        { title: '库位', dataIndex: 'locationName', width: 120 },
        { title: '总数量', dataIndex: 'totalQuantity', width: 100 },
        {
          title: '库存状态',
          dataIndex: 'stockStatus',
          width: 100,
          customRender: (text) => {
            const statusMap = {
              1: '正常',
              2: '预留',
              3: '冻结',
            }
            return statusMap[text] || text
          },
        },
      ],
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.handleSelectionChange,
        getCheckboxProps: (record) => ({
          disabled: record.availableQuantity <= 0,
        }),
      }
    },
  },
  methods: {
    add() {
      this.modalTitle = '新增出库单'
      this.visible = true
      this.model = {
        outboundNo: this.generateOutboundNo(),
        totalQuantity: 0,
      }
    },
    edit(record) {
      this.modalTitle = '编辑出库单'
      this.visible = true
      this.model = { ...record }
      if (record.orderNo) {
        this.loadOrderDetails(record.orderNo)
      }
    },
    close() {
      this.visible = false
      this.model = {}
      this.orderDetailList = []
      this.selectedRowKeys = []
      this.expandedRowKeys = []
      this.$refs.form && this.$refs.form.resetFields()
    },
    generateOutboundNo() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const time = String(now.getHours()).padStart(2, '0') + String(now.getMinutes()).padStart(2, '0')
      return `OUT${year}${month}${day}${time}`
    },
    async loadOrderDetails(orderNo) {
      try {
        // 首先通过订单编号获取订单ID
        const orderResponse = await this.$http.get('/oms/productSalesOrder/approvedList', {
          params: { orderNo: orderNo, pageSize: 1 },
        })

        if (!orderResponse.result || !orderResponse.result.records || orderResponse.result.records.length === 0) {
          this.$message.warning('未找到对应的订单信息')
          return
        }

        const orderId = orderResponse.result.records[0].id

        // 根据订单ID获取订单明细
        const detailResponse = await this.$http.get('/oms/productSalesOrder/detail/getDetailsByOrderId', {
          params: { orderId: orderId },
        })

        console.log('...........................  detailResponse......', detailResponse)
        if (detailResponse.success) {
          // 处理订单明细数据，添加库存相关字段
          this.orderDetailList = (detailResponse.result || []).map((detail) => ({
            ...detail,
            availableQuantity: detail.quantity || 0, // 暂时使用订单数量作为可出库数量，后续可根据实际库存调整
            inventoryList: [],
          }))

          // 计算总的可出库数量
          this.calculateTotalQuantity()
        } else {
          this.$message.error('获取订单明细失败：' + (detailResponse.message || '未知错误'))
        }
      } catch (error) {
        console.error('加载订单明细失败：', error)
        this.$message.error('加载订单明细失败：' + error.message)
      }
    },
    async loadInventoryByDetailId(detailId) {
      try {
        // 根据订单明细ID查询对应的库存信息
        const response = await this.$http.get(`/wms/finished-goods/inventory/by-order-detail/${detailId}`)
        if (response.success) {
          // 后端返回的是库存数组
          return response.result || []
        } else {
          this.$message.error('获取库存信息失败：' + (response.message || '未知错误'))
          return []
        }
      } catch (error) {
        console.error('加载库存信息失败：', error)
        this.$message.error('加载库存信息失败：' + error.message)
        return []
      }
    },
    async handleOrderChange(orderIds, selectedOrders) {
      if (!orderIds || !selectedOrders || selectedOrders.length === 0) {
        this.model.orderId = ''
        this.model.orderNo = ''
        this.model.customerName = ''
        this.model.projectName = ''
        this.orderDetailList = []
        this.selectedRowKeys = []
        this.model.totalQuantity = 0
        return
      }

      // 获取第一个选中的订单信息（单选模式）
      const selectedOrder = selectedOrders[0]
      if (selectedOrder) {
        this.model.orderId = selectedOrder.id
        this.model.orderNo = selectedOrder.orderNo
        this.model.customerName = selectedOrder.customerName
        this.model.projectName = selectedOrder.projectName
        // 加载订单明细
        await this.loadOrderDetails(selectedOrder.orderNo)
      }
    },
    async handleExpand(expanded, record) {
      if (expanded && (!record.inventoryList || record.inventoryList.length === 0)) {
        record.inventoryList = await this.loadInventoryByDetailId(record.id)
        this.$forceUpdate()
      }
    },
    async toggleExpand(record) {
      const isExpanded = this.expandedRowKeys.includes(record.id)
      if (isExpanded) {
        // 收起
        this.expandedRowKeys = this.expandedRowKeys.filter((key) => key !== record.id)
      } else {
        // 展开
        this.expandedRowKeys.push(record.id)
        // 如果没有库存数据，则加载
        if (!record.inventoryList || record.inventoryList.length === 0) {
          record.inventoryList = await this.loadInventoryByDetailId(record.id)
          this.$forceUpdate()
        }
      }
    },
    handleSelectionChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.calculateTotalQuantity()
    },
    calculateTotalQuantity() {
      let total = 0
      this.selectedRowKeys.forEach((key) => {
        const detail = this.orderDetailList.find((item) => item.id === key)
        if (detail) {
          total += detail.availableQuantity
        }
      })
      this.model.totalQuantity = total
    },
    filterOrderOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    async handleOk() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return

        if (this.selectedRowKeys.length === 0) {
          this.$message.warning('请至少选择一个订单明细！')
          return
        }

        this.confirmLoading = true
        try {
          const isEdit = !!this.model.id

          // 构建简化的明细数据，后端根据orderNo和订单明细ID查询库存信息
          const orderDetailList = this.selectedRowKeys.map((key) => {
            const detail = this.orderDetailList.find((item) => item.id === key)
            return {
              orderNo: detail.orderNo || this.model.orderNo,
              orderDetailId: detail.orderDetailId || detail.id,
              plannedQuantity: detail.quantity || detail.availableQuantity,
              remark: detail.remark || ''
            }
          })
          console.log('..........................', this.model)
          const submitData = {
            outboundNo: this.model.outboundNo,
            orderId: this.model.orderId,
            orderNo: this.model.orderNo,
            customerId: this.model.customerId || '',
            customerName: this.model.customerName || '',
            projectName: this.model.projectName || '',
            outboundType: 1, // 销售出库
            totalQuantity: this.model.totalQuantity || 0,
            totalAmount: this.model.totalAmount || 0,
            remark: this.model.remark || '',
            orderDetailList: orderDetailList
          }

          const url = isEdit ? '/wms/finished-goods/outbound/edit' : '/wms/finished-goods/outbound/add'

          const result = await this.$http[isEdit ? 'put' : 'post'](url, submitData)

          if (result.success) {
            this.$message.success(`${isEdit ? '编辑' : '新增'}成功！`)
            this.$emit('ok')
            this.close()
          } else {
            this.$message.error(result.message || '操作失败')
          }
        } catch (error) {
          console.error('提交出库单失败：', error)
          this.$message.error(
            '操作失败：' +
              (error.response && error.response.data && error.response.data.message
                ? error.response.data.message
                : error.message)
          )
        } finally {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.close()
    },
  },
}
</script>
